<script setup>
import { getOrderStatus, getOrderStatusInfo, updateOrderStatus,refundOrder } from "@/apis/order";
import { addReview } from "@/apis/review";
import { uploadImg } from "@/apis/upload";
import { getUserOrderAPI } from "@/apis/user";
import { userInfoStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
// tab列表
const tabTypes = [
  { name: "all", label: "全部订单" },
  { name: "unpay", label: "待付款" },
  { name: "deliver", label: "待发货" },
  { name: "receive", label: "待收货" },
  { name: "comment", label: "待评价" },
  { name: "complete", label: "已评价" },
  { name: "cancel", label: "已取消" },
  { name: "service", label: "售后" },
];

const activeName = ref(null);

// 订单列表
const orderList = ref([]);
const total = ref(0);
const params = ref({
  orderState: 0,
  page: 1,
  pageSize: 5,
});
const isLoding = ref(true);
const pageShow = ref(false);

const getOrderStatusList = async (status) => {
  console.log("status: ", status);
  let res = await getOrderStatus(userInfoStore().userInfo.userId, status);
  orderList.value = res.data;
  console.log("通过状态获取数据！！！",orderList.value)
  total.value = res.data.length;
  //   if (res.status === 200) {
  isLoding.value = false;
  pageShow.value = true;
  //   }
};

const getUserOrder = async () => {
  let res = await getUserOrderAPI(userInfoStore().userInfo.userId);
  orderList.value = res.data;
  total.value = res.data.length;
  //   if (res.status === 200) {
  isLoding.value = false;
  pageShow.value = true;
  //   }
};
onMounted(() => getUserOrder());

const tabChange = (type) => {
  console.log("type: ", type);
  params.value.orderState = type;
  pageShow.value = false;
  isLoding.value = true;
  console.log("activeName.value: ", activeName.value);
  if (activeName.value != 0) {
    if(type == 7)
  {
    getOrderStatusList(7);
  }else{
    getOrderStatusList(type - 1);
  }
  } else {
    getUserOrder();
  }
};

const pageChange = (page) => {
  window.scrollTo(0, 0);
  params.value.page = page;
  isLoding.value = true;
  getUserOrder();
};

const fomartPayState = (status) => {
  const stateMap = {
    3: "未付款",
    4: "待发货",
    5: "待收货",
    6: "待评价",
    7: "已评论",
    8: "已取消",
    2: "卖家同意退款",
    1: "卖家拒绝退款",
    0: "退款申请中",
  };
  return stateMap[status] || "未知状态";
};

const showRateDialog = ref(false);
const showDialog = ref(false);
const activeItem = ref({});

const order = ref({});
const neworderId = ref();
const newstatus = ref();
const openReview = (order,status) =>{
  showDialog.value = true;
  neworderId.value = order.orderId;
  newstatus.value = status;
};
const openRate = (item) => {
  showRateDialog.value = true;
  order.value = item;
  activeItem.value = item.products[0];
  console.log("activeItem.value: ", activeItem.value);
};

const rate = ref();
const comment = ref("");
const reason = ref("");
const imageUrls = ref([]);

const changeRate = (value) => {
  console.log("changeRate ", value);
  rate.value = value;
};

const switchProduct = (item) => {
  activeItem.value = item;
};

// 上传图片相关
const uploadImage = async (options) => {
  const { file } = options;
  const formData = new FormData();
  formData.append("file", file);

  try {
    const res = await uploadImg(formData);
    if (res.code === 200) {
      ElMessage.success("上传成功")
      options.onSuccess(res.message);
    } else {
      options.onError(new Error("上传失败"));
    }
  } catch (error) {
    options.onError(new Error("上传出错"));
    console.error(error);
  }
};

const handleUploadSuccess = (response, uploadFile) => {
  console.log("response: ", response);
  if (response) {
    imageUrls.value.push(response);
  }
};

const handleRemoveImage = (file, fileList) => {
  console.log("fileList: ", fileList);
  imageUrls.value = fileList;
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传1张图片`);
};

const beforeUpload = (rawFile) => {
  const isJPG = rawFile.type === "image/jpeg";
  const isPNG = rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("只能上传JPG或PNG格式的图片");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};

const confirm = async () => {
  const res = await addReview({
    orderId: order.value.orders.orderId,
    productId: activeItem.value.productId,
    userId: userInfoStore().userInfo.userId,
    rating: rate.value,
    comment: comment.value,
    images: imageUrls.value,
  });
  if (res.code === 200) {
    ElMessage.success("提交成功！");
    } else {
      ElMessage.error("提交失败！");
    }
    showRateDialog.value = false;
  console.log("res: ", res);
};


const router = useRouter();
// 获取订单详情
const getOrderInfo = async (order) => {
  const res = await getOrderStatusInfo(order.orderId);
  console.log("res: getOrderInfo ", res);
  if (res.code === 200) {
    router.push({
      path: "/pay",
      query: {
        orderId: order.orderId,
      },
    });
    // pageShow.value = false;
    // isLoding.value = true;
    // if (activeName.value) {
    //   getOrderStatusList(status);
    // } else {
    //   getUserOrder();
    // }
  }
};

// 更新订单状态
const updateNewStatus = async (order, newStatus, oldStatus) => {
  try {
    console.log("更改订单状态",order.orders.orderId,newStatus);
      await updateOrderStatus(order.orders.orderId,newStatus);
    ElMessage.success("操作成功！");
    console.log("newStatus:",newStatus);
    await getOrderStatusList(oldStatus); // 刷新订单列表
  } catch (error) {
    ElMessage.error("操作失败");
    console.error(error);
  }
};
// 退款

const updateStatus = async () => {
  const tjForm ={
    orderId: neworderId.value,
    reason: reason.value,
    images: imageUrls.value
  }

  console.log("退款--- ", tjForm);
  const res = await refundOrder(tjForm);

  showDialog.value = false;
  ElMessage.success("已提交退款申请！");

  await getOrderStatusList(newstatus.value);
};
</script>

<template>
  <div class="order-container">
    <el-tabs v-model="activeName" @tab-change="tabChange">
      <!-- tab切换 -->
      <el-tab-pane v-for="item in tabTypes" :key="item.name" :label="item.label" />

      <div class="main-container">
        <div class="holder-container" v-if="isLoding">
          <img src="../../../assets/images//loading.gif" />
        </div>
        <div class="holder-container" v-else-if="orderList.length === 0">
          <el-empty description="暂无订单数据" />
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <div class="head">
              <span>下单时间：{{ order.orders.createdAt }}</span>
              <span>订单编号：{{ order.orders.orderId }}</span>
              <!-- 未付款，倒计时时间还有 -->
              <span class="down-time" v-if="order.orders.status === 0">
                <i class="iconfont icon-down-time"></i>
                <b>付款截止: {{ order.orders.paymentDeadline }}</b>
              </span>
              <span class="down-time" v-if="order.orders.trackingNumber">
                <b>快递单号: {{ order.orders.trackingNumber }}</b>
              </span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="item in order.products" :key="item.productId">
                    <div class="image">
                      <!-- <RouterLink :to="`/detail/${i.productInfo.products.productId}`">
                        <img :src="item.productImg" alt="" />
                      </RouterLink> -->
                      <img :src="item.productImg" alt="" />
                    </div>
                    <div class="info">
                      <p class="name ellipsis-2">
                        {{ item.title }}
                      </p>
                      <p class="attr ellipsis">
                        <span>{{ item.tags }}</span>
                      </p>
                    </div>
                    <div class="price">¥{{ item.price?.toFixed(2) }}</div>
                    <!-- <div class="count">x{{ item.quantity }}</div> -->
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p>{{ fomartPayState(order.orders.status+3) }}</p>
                <!-- <p v-if="order.orders.orderType === 3">
                  <a href="javascript:;" class="green">查看物流</a>
                </p>
                <p v-if="order.orders.orderType === 4">
                  <a href="javascript:;" class="green">评价商品</a>
                </p>
                <p v-if="order.orders.orderType === 5">
                  <a href="javascript:;" class="green">查看评价</a>
                </p> -->
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.orders.totalAmount?.toFixed(2) }}</p>
                <p v-if="order.orders.deliveryMethod != 0">
                  地址：{{ order.orders?.deliveryAddress }}）
                </p>
                <p>{{ order.orders.deliveryMethod == 0 ? "自提" : "快递寄送" }}</p>
              </div>
              <div class="column action">
                <el-button
                  @click="getOrderInfo(order.orders)"
                  v-if="order.orders.status === 0"
                  type="primary"
                  size="small"
                >
                  立即付款
                </el-button>
                <el-button
                  @click="openReview(order.orders,order.orders.status)"
                  v-if="[1, 3, 4].includes(order.orders.status)"
                  type="primary"
                  size="small"
                >
                  申请退款
                </el-button>
                <el-button
                  @click="updateNewStatus(order, 3,2)"
                  v-if="[2].includes(order.orders.status)"
                  type="primary"
                  size="small"
                >
                  确认收货
                </el-button>
                <!-- <p><a href="javascript:;">查看详情</a></p> -->
                <p v-if="[3].includes(order.orders.status)">
                  <a href="javascript:;" @click="openRate(order)">去评价</a>
                </p>
                <p v-if="[5].includes(order.orders.status)">
                  <RouterLink :to="`/detail/${order.products[0].productId}`">
                    再次购买</RouterLink
                  >
                </p>
                <p
                  v-if="order.orders.status === 0"
                  @click="updateNewStatus(order.orders, 5)"
                >
                  <a href="javascript:;">取消订单</a>
                </p>
              </div>
            </div>
          </div>
        </div>
        <!-- 分页 -->
        <!-- <div v-if="pageShow" class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="params.pageSize"
            @current-change="pageChange"
          />
        </div> -->
      </div>
    </el-tabs>
<!--退款弹出框-->
    <el-dialog v-model="showDialog" title="申请退款" width="50%" center>
      <div class="addressWrapper">
          <ul>
            <li>
              <span style="margin-bottom: 50px;">退款原因：</span
              ><el-input
                v-model="reason"
                autosize
                type="textarea"
                placeholder="请输入退款原因"
              />
            </li>
            <li style="margin: 10px 0; display: flex; gap: 10px">
              <span> 上传图片： </span>
              <el-upload
                action=""
                :http-request="uploadImage"
                :file-list="imageUrls"
                :on-success="handleUploadSuccess"
                :on-remove="handleRemoveImage"
                list-type="picture-card"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
              >
                <i class="el-icon-plus"></i>
                <div class="el-upload__text">点击上传</div>
              </el-upload>
            </li>
          </ul>
        </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="updateStatus()">提交</el-button>
          <el-button @click="showDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!--评论弹出框-->
    <el-dialog v-model="showRateDialog" title="商品评价" width="50%" center>
      <div class="addressWrapper">
        <div
          class="text item"
          v-for="(item, index) in order.products"
          :key="item.productId"
          @click="switchProduct(item)"
          :class="{
            active: activeItem.productId === item.productId,
          }"
        >
          <!-- @click="switchAddress(item)" -->
          <ul>
            <li><span>商品名称：</span>{{ item.title }}</li>
            <li><span>商品信息：</span>{{ item.description }}</li>
            <li><span>商品价格：</span>{{ item.price }}</li>
            <li>
              <span>评&ensp;&ensp;&ensp;&ensp;分：</span
              ><el-rate v-model="rate" allow-half size="large" @change="changeRate" />
t            </li>
            <li style="margin: 10px 0; display: flex; gap: 10px">
              <span> 上传图片： </span>
              <el-upload
                action=""
                :http-request="uploadImage"
                :file-list="imageUrls"
                :on-success="handleUploadSuccess"
                :on-remove="handleRemoveImage"
                list-type="picture-card"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
              >
                <i class="el-icon-plus"></i>
                <div class="el-upload__text">点击上传</div>
              </el-upload>
            </li>
            <li>
              <span>评&ensp;&ensp;&ensp;&ensp;论：</span
              ><el-input
                v-model="comment"
                style="width: 240px"
                autosize
                type="textarea"
                placeholder="请评论"
              />
              <el-button style="margin-left: 100px" type="primary" @click="confirm"
                >提交</el-button
              >
            </li>
          </ul>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRateDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: stretch;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      > p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

      &.state {
        width: 120px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}

.addressWrapper {
  max-height: 500px;
  overflow-y: auto;
}

.text {
  flex: 1;
  min-height: 90px;
  display: flex;
  align-items: center;

  &.item {
    border: 1px solid #f5f5f5;
    margin-bottom: 10px;
    cursor: pointer;

    &.active,
    &:hover {
      border-color: $xtxColor;
      background: lighten($xtxColor, 50%);
    }

    > ul {
      padding: 10px;
      font-size: 14px;
      line-height: 30px;
    }
  }
}
</style>
